{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "\n",
    "sys.path.append('../utils')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import re\n",
    "\n",
    "from aoc import * # get_input, d4, d8, d4n\n",
    "from itertools import product\n",
    "from functools import reduce"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "YEAR = 2021\n",
    "DAY = 22"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "sample = '''on x=10..12,y=10..12,z=10..12\n",
    "on x=11..13,y=11..13,z=11..13\n",
    "off x=9..11,y=9..11,z=9..11\n",
    "on x=10..10,y=10..10,z=10..10'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "inp = get_input(YEAR, DAY)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def do_transform(inp):\n",
    "    return list(filter(lambda x: len(x) > 0, inp.split('\\n')))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "sample = do_transform(sample)\n",
    "inp = do_transform(inp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "class KDNode:\n",
    "    def __init__(self, region, state):\n",
    "        self.region = region\n",
    "        self.state = state\n",
    "        self.children = []\n",
    "        \n",
    "    def outside_of(self, region):\n",
    "        return any(map(lambda x: x[1][0] >= x[0][1] or x[1][1] <= x[0][0], zip(self.region, region)))\n",
    "        \n",
    "    def contained_by(self, region):\n",
    "        return all(map(lambda x: x[1][0] <= x[0][0] < x[0][1] <= x[1][1], zip(self.region, region)))\n",
    "        \n",
    "    def set_state(self, region, state):\n",
    "        if self.outside_of(region):\n",
    "            return\n",
    "        elif self.contained_by(region):\n",
    "            self.state = state\n",
    "            self.children = []\n",
    "            return\n",
    "        elif len(self.children) == 0:\n",
    "            sub = []\n",
    "            for (l, r), (l1, r1) in zip(self.region, region):\n",
    "                pts = sorted(list(set(filter(lambda x: l <= x <= r, [l, r, l1, r1]))))\n",
    "                sub.append(list(zip(pts[:-1], pts[1:])))\n",
    "            self.children = list(map(lambda x: KDNode(x, self.state), product(*sub)))\n",
    "\n",
    "        for child in self.children:\n",
    "            child.set_state(region, state)\n",
    "            \n",
    "    def value(self):        \n",
    "        if len(self.children) == 0:\n",
    "            return reduce(lambda x, y: x * y, map(lambda x: x[1] - x[0], self.region), 1) if self.state else 0\n",
    "        return sum(child.value() for child in self.children)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def solve(inp, k, inf):\n",
    "    root = KDNode([(-inf, inf + 1)] * k, False)\n",
    "    \n",
    "    for state, xs, xe, ys, ye, zs, ze in map(lambda x: (x.split()[0], *map(int, re.findall(r'-?\\d+', x.split()[1]))), inp):\n",
    "        root.set_state([(xs, xe + 1), (ys, ye + 1), (zs, ze + 1)], state == 'on')\n",
    "        \n",
    "    return root.value()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def part1(inp):\n",
    "    return solve(inp, 3, 50)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "39"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "part1(sample)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "648681"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "part1_ans = part1(inp)\n",
    "part1_ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "submit_answer(part1_ans, YEAR, DAY)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "def part2(inp):\n",
    "    return solve(inp, 3, 1000000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "39"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "part2(sample)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1302784472088899"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "part2_ans = part2(inp)\n",
    "part2_ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "submit_answer(part2_ans, YEAR, DAY, level=2)"
   ]
  }
 ],
 "metadata": {
  "@webio": {
   "lastCommId": null,
   "lastKernelId": null
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.12"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
